package com.yihecode.camera.ai.web;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yihecode.camera.ai.entity.Camera;
import com.yihecode.camera.ai.entity.WareHouse;
import com.yihecode.camera.ai.service.CameraService;
import com.yihecode.camera.ai.service.WareHouseService;
import com.yihecode.camera.ai.utils.JsonResult;
import com.yihecode.camera.ai.utils.JsonResultUtils;
import com.yihecode.camera.ai.utils.PageResult;
import com.yihecode.camera.ai.utils.PageResultUtils;
import com.yihecode.camera.ai.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 基地管理， 树形结构管理， 适配中华定制需求
 * 省 -> 市 -> 基地
 *
 * @author zhoumingxing
 * @mail 465769438@qq.com
 */
@SaCheckLogin
@Controller
@RequestMapping({"/warehouse"})
public class WareHouseController {

    @Autowired
    private WareHouseService wareHouseService;

    @Autowired
    private CameraService cameraService;

    /**
     *
     * @return
     */
    @GetMapping({"", "/"})
    public String index(ModelMap modelMap) {
        int count = wareHouseService.count();
        modelMap.addAttribute("count", count);
        return "warehouse/index";
    }

    /**
     *
     * @param parentId
     * @param modelMap
     * @return
     */
    @GetMapping({"/form"})
    public String form(Long parentId, ModelMap modelMap) {
        if(parentId == null || parentId == -1) {
            modelMap.addAttribute("parentId", "");
        } else {
            modelMap.addAttribute("parentId", parentId);
        }
        return "warehouse/form";
    }

    /**
     *
     * @param id
     * @param modelMap
     * @return
     */
    @GetMapping({"/form2"})
    public String form2(Long id, ModelMap modelMap) {
        WareHouse wareHouse = wareHouseService.getById(id);
        modelMap.addAttribute("warehouse", wareHouse);
        //modelMap.addAttribute("parentId", wareHouse == null ? null : wareHouse.getParentId());
        return "warehouse/form";
    }

    /**
     *
     * @return
     */
    @PostMapping({"/listPage"})
    @ResponseBody
    public PageResult listPage(String parentIndexCode, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
        IPage<WareHouse> pageObj = new Page<>(page, limit);
        IPage<WareHouse> pageResult = wareHouseService.listPage(pageObj, parentIndexCode);
        return PageResultUtils.success(pageResult.getTotal(), pageResult.getRecords());
    }

    /**
     * tree
     * @return
     */
    @RequestMapping(value = "/listTree")
    @ResponseBody
    public List<TreeVo> listTree() {
        List<WareHouse> wareHouseList = wareHouseService.listAll();

        //
        List<TreeVo> treeVoList = new ArrayList<>();
        for(WareHouse wareHouse : wareHouseList) {
            TreeVo treeVo = new TreeVo();
            treeVo.setMeId(wareHouse.getIndexCode());
            treeVo.setText(wareHouse.getName());
            treeVo.setParent(wareHouse.getParentIndexCode());
            treeVo.setChildren(new ArrayList<>());
            if(wareHouse.getTreeType() == null || wareHouse.getTreeType() == 0) {
                treeVo.setIcon("layui-icon layui-icon-home");
            } else {
                treeVo.setIcon("layui-icon layui-icon-location");
            }

            treeVoList.add(treeVo);
        }

        //
        List<TreeVo> trees = new ArrayList<>();
        for(TreeVo treeVo : treeVoList) {
            if(treeVo.getParent().equals("-1")) {
                treeVo.setParent("#");
                trees.add(findChildren(treeVo, treeVoList));
            }
        }
        return trees;
    }

    //
    private TreeVo findChildren(TreeVo tree, List<TreeVo> treeList) {
        for(TreeVo node : treeList) {
            if(tree.getMeId().equals(node.getParent())) {
                if(tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<>());
                }
                tree.getChildren().add(findChildren(node, treeList));

            }
        }
        return tree;
    }

    /**
     * 全量同步
     * @return
     */
    @PostMapping({"/sync2all"})
    @ResponseBody
    public JsonResult sync2all() {
        return JsonResultUtils.success();
    }

    /**
     * 增量同步
     * @param indexCode
     * @return
     */
    @PostMapping({"/sync2node"})
    @ResponseBody
    public JsonResult sync2all(String indexCode) {
        if(StrUtil.isBlank(indexCode)) {
            return JsonResultUtils.fail("没有选中节点");
        }
        return JsonResultUtils.success();
    }

    /**
     * 拉取摄像头地址
     * @param indexCode
     * @return
     */
    @PostMapping({"/pullRtsp"})
    @ResponseBody
    public JsonResult pullRtsp(String indexCode) {
        if(StrUtil.isBlank(indexCode)) {
            return JsonResultUtils.fail("没有选中节点");
        }

        //
        WareHouse wareHouse = wareHouseService.getByIndexCode(indexCode);
        if(wareHouse == null) {
            return JsonResultUtils.fail("没有找到节点信息");
        }

        //
        if(wareHouse.getTreeType() == null || wareHouse.getTreeType() != 0) {
            return JsonResultUtils.fail("当前节点下面没有监控点信息");
        }

        //
        List<WareHouse> wareHouseList = wareHouseService.listChildren(indexCode);
        if(wareHouseList.isEmpty()) {
            return JsonResultUtils.fail("当前节点下面没有监控点信息");
        }

        return JsonResultUtils.success();
    }

    /**
     * 导入摄像头管理
     * @param ids
     * @return
     */
    @PostMapping({"/select2export"})
    @ResponseBody
    public JsonResult select2export(String ids) {
        if(StrUtil.isBlank(ids)) {
            return JsonResultUtils.fail("请选中要导入的数据");
        }

        String[] idArr = ids.split(",");
        for(String idStr : idArr) {
            WareHouse wareHouse = wareHouseService.getById(Long.parseLong(idStr));
            if(wareHouse == null || wareHouse.getTreeType() == null || wareHouse.getTreeType() == 0 || StrUtil.isBlank(wareHouse.getRtspUrl())) {
                continue;
            }

            //
            Camera camera = cameraService.getByWareHouseId(wareHouse.getId());
            if(camera != null && camera.getState() != null && camera.getState() == 0) { // 摄像头已存在，且为有效状态
                continue;
            }

            //
            Camera newCamera = new Camera();
            newCamera.setName(wareHouse.getName());
            newCamera.setRtspUrl(wareHouse.getRtspUrl());
            newCamera.setAction(0);
            newCamera.setRunning(0);
            newCamera.setState(0);
            newCamera.setCreatedAt(new Date());
            newCamera.setUpdatedAt(new Date());
            newCamera.setFrequency(1000);
            newCamera.setIntervalTime(10f);
            newCamera.setFileWidth(0);
            newCamera.setFileHeight(0);
            newCamera.setCanvasWidth(0);
            newCamera.setCanvasHeight(0);
            newCamera.setScaleRatio(0f);
            newCamera.setWareHouseId(wareHouse.getId());
            cameraService.save(newCamera);
        }


        return JsonResultUtils.success();
    }

    /**
     *
     * @param wareHouse
     * @return
     */
    @PostMapping({"/save"})
    @ResponseBody
    public JsonResult save(WareHouse wareHouse) {
        return JsonResultUtils.success();
    }

    /**
     *
     * @param id
     * @return
     */
    @PostMapping({"/delete"})
    @ResponseBody
    public JsonResult delete(Long id) {
        return JsonResultUtils.success();
    }
}